using ED.Common;
using ED.Common.BaseModel;
using ED.Common.Extensions;
using ED.IRepository;
using ED.IService;
using ED.Model.Request;
using ED.Model.Response;

/// <summary>
/// RolePermission服务
/// </summary>
namespace ED.Service
{
    public class RolePermissionService : IRolePermissionService
    {
        private readonly IRolePermissionRepository rolepermissionRepository;
        public RolePermissionService(IRolePermissionRepository rolepermissionRepository)
        {
            this.rolepermissionRepository = rolepermissionRepository;
        }

        /// <summary>
        /// RolePermission添加
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Tuple<bool, string> Add(RolePermissOperateReq req)
        {
            // 字段校验
            var resEntity = rolepermissionRepository.Get(t => t.RoleId == req.RoleId);
            if (!resEntity.IsDefault())
            {
                ThrowHelp.Throw("该角色已存在");
            }
            resEntity.PermissionId = string.Join(',', req.PermissionIds);
            var res = rolepermissionRepository.Insert(resEntity);
            return res.IsDefault() ? new Tuple<bool, string>(false, "保存失败") : new Tuple<bool, string>(true, "保存成功");
        }

        /// <summary>
        /// RolePermission删除
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Tuple<bool, string> Delete(int req)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// RolePermission查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public PageOut<RolePermissRes> Page(RolePermissReq req)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// RolePermission更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Tuple<bool, string> Update(RolePermissOperateReq req)
        {
            // 字段校验
            var resEntity = rolepermissionRepository.Get(t => t.RoleId == req.RoleId);
            if (resEntity.IsDefault()) 
            {
                ThrowHelp.Throw("该角色不存在");
            }
            resEntity.PermissionId = string.Join(',', req.PermissionIds);
            var res = rolepermissionRepository.Update(resEntity);
            return res.IsDefault() ? new Tuple<bool, string>(false, "保存失败") : new Tuple<bool, string>(true, "保存成功");
        }
    }
}
